<template>
  <page-header-wrapper>
    <page-tab-list></page-tab-list>
    <a-card :bordered="false" class="card_style_re">
      <div class="flex-x-sb flex-y-center" style="margin-bottom: 16px">
        <span></span>
        <div>
          <a-button type="primary" @click="onAdd" icon="plus">新建</a-button>
          <a-dropdown style="margin-left: 10px" :trigger="['hover']">
            <a-button>批量操作 <a-icon type="down" /></a-button>
            <a-menu slot="overlay">
              <a-menu-item key="0">
                <a-popconfirm title="确认删除选中卡劵吗？" @confirm="handleDelete(record, 'check')">
                  批量删除
                </a-popconfirm>
              </a-menu-item>
              <!-- <a-menu-item key="1"> 批量导入 </a-menu-item>
              <a-menu-item key="2"> 批量导出 </a-menu-item>
              <a-menu-item key="3"> 批量生成 </a-menu-item> -->
            </a-menu>
          </a-dropdown>
        </div>
      </div>

      <!-- <div v-show="selectedRowKeys1.length" class="select-title">
        <a-alert :message="`已选择 ${selectedRowKeys1.length} 项`" type="info" show-icon />
      </div>
      <a-divider /> -->
      <STable
        :row-selection="{ selectedRowKeys: selectedRowKeys1, onChange: onSelectChange1 }"
        rowKey="id"
        :alert="true"
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <span slot="name" slot-scope="text, item">
          <div class="flex">
            <img :src="item.pic_url" style="width: 45px; height: 45px; border-radius: 5px; margin-right: 10px" alt="" />
            <div>
              <div>{{ item.name }}</div>
              <!-- <div style="color: #999">{{ item.type }}</div> -->
              <span v-for="item1 in CARD_TYPE" :key="item1.value">
                <span v-show="item.type == item1.value">
                  {{ item1.text }}
                </span>
              </span>
            </div>
          </div>
        </span>

        <span slot="num" slot-scope="num">
          <span>{{ !num ? '无限量' : num }}</span>
        </span>

        <!-- 有效时间 -->
        <span slot="expire_day" slot-scope="text, record">
          <span v-if="record.date_type == 1">{{ `领取后${text == 0 ? '永久有效' : text + '天有效'}` }}</span>
          <span v-else-if="record.date_type == 2">{{ record.begin_time }}至{{ record.end_time }}</span>
          <span v-else>{{ text }}</span>
        </span>

        <!-- 操作 -->
        <span class="flex-y-center" slot="action" slot-scope="text, record">
          <div>
            <a-button type="link" @click="handleTable(record)" size="small">查看</a-button>
            <!-- <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button> -->
          </div>
          <a-dropdown style="margin-left: 10px" :trigger="['hover']">
            <a>更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item key="0" @click="handleEdit(record)"> 编辑 </a-menu-item>
              <!-- <a-menu-item key="1"> 生成 </a-menu-item> -->
              <a-menu-item key="2">
                <a-popconfirm title="确认删除该卡劵吗？" @confirm="handleDelete(record)"> 删除 </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </STable>
    </a-card>

    <!-- 新增编辑 -->
    <a-modal
      :title="isNew ? '创建卡劵' : '编辑卡劵'"
      :width="800"
      :confirm-loading="modalLoading"
      :mask-closable="false"
      :destroy-on-close="true"
      :bodyStyle="{ height: '600px', overflow: 'auto' }"
      v-model="visible"
      @ok="handleOk"
    >
      <el-form
        :rules="modifyRules"
        label-width="120px"
        :model="modifyForm"
        label-suffix="："
        ref="modifyForm"
        size="small"
      >
        <!-- logo图 -->
        <el-form-item label="logo" style="display: inlin-block" prop="pic_url">
          <span style="display: inline-block">
            <cyyUploadImg
              :imgSrc="modifyForm.pic_url"
              @uploadSuccess="(data) => (this.modifyForm.pic_url = data.data)"
              imgSizeText="100*100"
            />
          </span>
        </el-form-item>

        <!-- 背景图 -->
        <el-form-item label="背景图" prop="bg_pic_url">
          <span style="display: inline-block">
            <cyyUploadImg
              :imgSrc="modifyForm.bg_pic_url"
              @uploadSuccess="(data) => (this.modifyForm.bg_pic_url = data.data)"
              imgSizeText="702*380"
            />
          </span>
        </el-form-item>

        <!-- 名称 -->
        <el-form-item label="名称" prop="name">
          <el-input v-model="modifyForm.name" placeholder=""></el-input>
        </el-form-item>

        <!-- 时间类型 -->
        <el-form-item label="有效时间" prop="date_type">
          <a-radio-group v-model="modifyForm.date_type">
            <a-radio value="1">领取后</a-radio>
            <a-radio value="2">固定时间</a-radio>
          </a-radio-group>
        </el-form-item>

        <!-- 领取后天数 -->
        <div v-if="modifyForm.date_type == 1">
          <el-form-item label="输入时间" :prop="modifyForm.date_type == 1 ? 'expire_day' : ''">
            <a-input-number
              placeholder="有效天数"
              :formatter="(value) => `${value}天`"
              :min="0"
              v-model="modifyForm.expire_day"
            />
          </el-form-item>
        </div>
        <!-- 固定天数 -->
        <div v-else-if="modifyForm.date_type == 2">
          <el-form-item label="选择时间" :prop="modifyForm.date_type == 2 ? 'date' : ''">
            <a-range-picker
              v-model="date"
              placeholder="请选择有限天数"
              @change="onChange"
              valueFormat="YYYY-MM-DD"
              format="YYYY-MM-DD"
              :allowClear="false"
            />
          </el-form-item>
        </div>

        <!-- 卡劵价值 -->
        <el-form-item label="卡劵价值" prop="price">
          <a-input-number
            placeholder="卡劵价值"
            :formatter="(value) => `${value}元`"
            :parser="(value) => value.replace('元', '')"
            :min="0"
            :precision="2"
            :step="0.01"
            v-model="modifyForm.price"
          />
        </el-form-item>

        <!-- 核销卡 -->
        <div v-if="modifyForm.type == 1">
          <el-form-item label="核销次数" :prop="modifyForm.type == 1 ? 'total_num' : ''">
            <a-input-number placeholder="核销次数" :min="1" v-model="modifyForm.total_num" />
          </el-form-item>
        </div>

        <!-- 富文本 -->
        <el-form-item label="说明" prop="content">
          <WangEditor
            @change="(v) => (this.modifyForm.content = v)"
            :value.sync="modifyForm.content"
            :autoFocus="true"
          ></WangEditor>
        </el-form-item>
      </el-form>
    </a-modal>

    <!-- 卡劵发放 -->
    <a-modal
      title="卡卷发放"
      :width="800"
      :confirm-loading="modalLoading"
      :bodyStyle="{ height: '600px', overflow: 'auto' }"
      :mask-closable="false"
      :destroy-on-close="true"
      v-model="cardShow"
      @ok="cardShow = false"
    >
      <ATable :data="cardList" bordered ref="cardTable" size="small" :columns="cardColumns"> </ATable>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { STable, WangEditor } from '@/components'
import { cyyUploadImg } from '@/components/CyyUi'
import { verifyList, verifyDel, verifyAdd, verifyEdit, verifyCardBatch } from '@/api/marketing'
import moment from 'moment'

const CARD_TYPE = [
  {
    text: '核销卡',
    value: 1,
  },
  {
    text: '礼品卡',
    value: 2,
  },
  {
    text: '储值卡',
    value: 3,
  },
  {
    text: '卡密卡',
    value: 4,
  },
  {
    text: '视频卡',
    value: 5,
  },
]

// 核销卡列表
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 60,
  },
  {
    title: '卡劵名称',
    dataIndex: 'name',
    scopedSlots: {
      customRender: 'name',
    },
    width: 350,
  },

  {
    title: '已发放数量',
    dataIndex: 'send_times',
    sorter: (a, b) => a.send_times - b.send_times,
  },
  {
    title: '卡卷总数',
    dataIndex: 'num',
    scopedSlots: {
      customRender: 'num',
    },
    sorter: (a, b) => a.num - b.num,
  },

  {
    title: '创建时间',
    dataIndex: 'created_at',
    width: 200,
    sorter: (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
  },
  {
    title: '有效时间',
    dataIndex: 'expire_day',
    scopedSlots: {
      customRender: 'expire_day',
    },
  },

  {
    title: '操作',
    width: 200,
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

// 核销卡领取列表
const cardColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '卡劵名称',
    dataIndex: 'name',
  },
  {
    title: '卡劵类型',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' },
  },
  {
    title: '卡密',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' },
  },
  {
    title: '所有者',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' },
  },
  {
    title: '生成时间',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' },
  },
  {
    title: '剩余次数',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' },
  },
]

export default {
  name: 'ArticleList',
  components: {
    STable,
    WangEditor,
    cyyUploadImg,
  },
  data() {
    return {
      CARD_TYPE,
      videoList: [], // 选中的视频列表
      videoShow: false,
      selectedRowKeys1: [],
      cardList: async (parameter) => {
        console.log(parameter)
        return []
      }, // 核销卡领取列表
      cardShow: false, // 卡卷发放弹框开关
      selectGoods: [], // 确定选中的的商品
      selectedRowKeys: [], // 选中的商品
      goodsShow: false, // 商品列表弹框开关
      type: 1, // 卡类型 1核销卡 2礼品卡 3储值卡
      date_type: 1, // 有效期类型 1领取N天 2固定时间
      form_content: '', // 富文本默认value
      cardColumns,
      isNew: false,
      visible: false,
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      // form: this.$form.createForm(this),
      modifyRules: {
        pic_url: [{ required: true, message: '请上传logo图片' }],
        bg_pic_url: [{ required: true, message: '请上传背景图片' }],
        name: [{ required: true, message: '请输入名称' }],
        type: [{ required: true }],
        date_type: [{ required: true }],
        expire_day: [{ required: true, message: '请输入有效时间' }],
        date: [{ required: true, message: '请选择固定时间', trigger: 'change' }],
        price: [{ required: true, message: '请输入卡劵价值' }],
        num: [{ required: true, message: '请输入卡劵数量', trigger: 'blur' }],
        total_num: [{ required: true, message: '请输入核销次数' }],
        is_give: [{ required: true }],
        content: [{ required: true, message: '请输入说明内容', trigger: 'blur' }],
      },
      modifyForm: {
        pic_url: '', // logo图
        bg_pic_url: '', // 背景图
        name: '', // 名称
        type: '1', // 核销卡类型
        date_type: '1', // 时间类型
        expire_day: '0', // 时间天
        date: [], // 时间日期
        price: 0, // 卡劵价值
        is_give: '0', // 是否转增
        content: '', // 说明
        // num: 1, // 卡劵数量
        total_num: 1, // 核销次数
        total_price:1,
        is_business:1,
        business_type:1
      },
      // 表头
      columns,
      modalLoading: false,
      statusSelectValue: {
        key: '1',
        label: '显示',
      },
      type_list: [],
      form_pic_url: '',
      bg_pic_url: '',
      // 查询条件参数
      queryParam: {
        search_key: null,
        type: 0,
        date: null,
        is_business:1
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        return verifyList(parameter)
          .then((res) => {
            console.log('VerifyList', res)
            this.type_list = res.data.type_list
            return res.data
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.$refs.table.localLoading = false
          })
      },
      // 修改卡券绑定的时间
      date: [],
    }
  },
  methods: {
    // 跳转卡劵详情
    handleTable(item) {
      this.$router.push('/marketing/saas-verify-detail?id=' + item.id)
    },
    // table表选择
    onSelectChange1(value) {
      console.log(value)
      this.selectedRowKeys1 = value
    },
    // 点击编辑
    handleEdit(record) {
      this.isNew = false
      this.visible = true
      console.log(record)
      var item = JSON.parse(JSON.stringify(record))
      this.modifyForm = item
      if (item.date_type == 2) {
        this.modifyForm.date = [item.begin_time, item.end_time]
        this.date = [item.begin_time, item.end_time]
      }
      // 选中视频赋值
      this.videoList = item.videolist
      this.selectGoods = item.goodlist

      // record.layout = parseInt(record.layout)
      // record.is_chosen = parseInt(record.is_chosen)
      // record.is_show = parseInt(record.is_show)
      // this.form_pic_url = record.pic_url
      // this.$nextTick(() => {
      //   this.form.setFieldsValue(
      //     pick(record, ['id', 'name', 'pic_url', 'expire_day', 'total_num', 'money', 'price', 'sort'])
      //   )
      // })
    },
    handleOk() {
      console.log(this.modifyForm)
      this.$refs.modifyForm.validate(async (value) => {
        if (!value) return false
        this.modalLoading = true
        try {
          if (this.isNew) {
            const res = await verifyAdd(this.modifyForm)
            if (res.code != 0) throw res
            this.$message.success(res.msg)
          } else {
            const res = await verifyEdit(this.modifyForm)
            if (res.code != 0) throw res
            this.$message.success(res.msg)
          }
          this.modalLoading = false
          this.visible = false
          this.$refs.table.refresh()
          this.modifyForm = this.$options.data().modifyForm
        } catch (err) {
          this.modalLoading = false
          this.$message.error(err.msg)
        }
      })
      return
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        Object.assign(values, {
          pic_url: this.form_pic_url,
        })
        this.modalLoading = true
        if (this.isNew) {
          verifyAdd(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('核销卡创建成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        } else {
          verifyEdit(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('核销卡编辑成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
    onAdd: function () {
      this.modifyForm = this.$options.data().modifyForm
      this.isNew = true
      this.visible = true
      // this.form_pic_url = ''
    },
    async handleDelete(record, check) {
      try {
        const hide = this.$message.loading('删除中...', 0)

        if (check) {
          const res = await verifyCardBatch({ id: this.selectedRowKeys1, status: 1 })
          if (res.code != 0) throw res
        } else {
          const res = await verifyDel({ id: record.id })
          if (res.code != 0) throw res
        }
        hide()
        this.$message.success('核销卡删除成功！')
        this.$refs.table.refresh()
      } catch (error) {
        this.$message.error(error.message)
        this.modalLoading = false
        this.$error({
          content: error.msg,
        })
      }
    },
    moment,
    onChange(e) {
      this.modifyForm.date = e
      console.log(this.modifyForm.date);
    }
  },
  mounted() {
  },
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.ant-input-number {
  width: 100%;
}
.picItem {
  position: relative;
  margin-top: 8px;
  .icon {
    position: absolute;
    top: -5px;
    right: -5px;
    font-size: 20px;
    cursor: pointer;
    color: #ff4000;
  }
}
</style>
